//
//  WXAlbumModule.swift
//  mlz
//
//  Created by 吕凌 on 2018/4/14.
//  Copyright © 2018年 吕凌. All rights reserved.
//

import Foundation

public extension WXAlbumModule {
    
    @objc public func saveDataUrl(_ dataUrl: String, callback: @escaping WXModuleKeepAliveCallback) {
        UIImageWriteToSavedPhotosAlbum(self.base64StringToUIImage(base64String: dataUrl)!, nil, nil, nil)
        callback(true, false)
    }
    
    @objc public func saveUrl(_ url: String, callback: @escaping WXModuleKeepAliveCallback) {
        let data: NSData? = NSData(contentsOf: URL(string: url)!)
        UIImageWriteToSavedPhotosAlbum(UIImage(data: data! as Data)!, nil, nil, nil)
        callback(true, false)
    }
    
    func base64StringToUIImage(base64String:String)->UIImage? {
        var str = base64String
        
        // 1、判断用户传过来的base64的字符串是否是以data开口的，如果是以data开头的，那么就获取字符串中的base代码，然后在转换，如果不是以data开头的，那么就直接转换
        if str.hasPrefix("data:image") {
            guard let newBase64String = str.components(separatedBy: ",").last else {
                return nil
            }
            str = newBase64String
        }
        // 2、将处理好的base64String代码转换成NSData
        guard let imgNSData = NSData(base64Encoded: str, options: NSData.Base64DecodingOptions()) else {
            return nil
        }
        // 3、将NSData的图片，转换成UIImage
        guard let codeImage = UIImage(data: imgNSData as Data) else {
            return nil
        }
        return codeImage
    }
}
